import { useState, useEffect,Fragment } from 'react'
import axios from 'axios';

// 考题 自定义一个hooks，hooks 就是一个封装的函数
const useHackerNewsApi = (query) => {
  
  const [url,setUrl] = useState(`https://hn.algolia.com/api/v1/search?search=${query}`);
  const [data, setData] = useState({hits: []});
  const [isLoading,setIsLoading] = useState(false);
  const [isError,setIsError] = useState(false);

  useEffect(async () => {
    
    const fetchData = async () => {
      console.log(url);
      setIsLoading(true);
      try{
        const result = await axios(url);
        setData(result.data); 
      }catch(err) {
        setIsError(true);
      }
      
      setIsLoading(false);
       
    }

    fetchData();
  },[url]);

  return [{data,isLoading,isError},setUrl];
}


// 组件的状态：加载中、成功、错误
function App() {
  
  const [query,setQuery] = useState('redux');
  const [{data,isError,isLoading},setUrl] = useHackerNewsApi(query);


  return (

    <Fragment >

      <form onSubmit={(e) => {
        e.preventDefault();
        setUrl(`https://hn.algolia.com/api/v1/search?search=${query}`)
        
        }} >
      <input type="text" value={query} onChange={ event => setQuery(event.target.value)} />
      <button type="submit" >提交</button>

      </form>
      
      
      {
        isLoading
          ?<div> 加载中。。。。</div>
          :<ul>
              {data.hits.map(item => (
                <li key={item.ObjectID}>
                  <a href="{item.url}">{item.title}</a>
                </li>
              ))}
            </ul>
      }
      
      { isError && <div>Something is error ....</div>}
      
      
    </Fragment>
    
  )
}

export default App